package top.taooc.serializer;

import java.io.*;

/**
 * @author songtao@guishangyi.cn
 * @date 2024年06月25日 15:44:45
 * @packageName top.taooc.taooc.rpc.easy.serializer
 * @className JdkSerializer
 * @Menu
 */
public class JdkSerializer implements Serializer{
    /**
     * 序列化
     *
     * @param object
     * @return
     * @throws IOException
     */
    @Override
    public <T> byte[] seriailize(T object) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return outputStream.toByteArray();
    }

    /**
     * 反序列化
     *
     * @param bytes
     * @param type
     * @return
     * @throws IOException
     */
    @Override
    public <T> T deserialize(byte[] bytes, Class<T> type) throws IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        try {
            return (T) objectInputStream.readObject();
        }catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        }finally {
            objectInputStream.close();
        }
    }
}
